import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 读取JSON文件中的用户数据
export const getAuditorsFromFile = () => {
  try {
    const dataPath = path.join(__dirname, '../data/users.json');
    const auditorsData = fs.readFileSync(dataPath, 'utf8');
    return JSON.parse(auditorsData);
  } catch (error) {
    console.error('Error reading auditors data:', error);
    return [];
  }
};

/**
 * 获取用户基本信息
 * @route GET /api/auditors/:id
 * @param {string} id - 用户ID
 * @returns {object} 用户基本信息
 */
export const getAuditorById = (req, res) => {
  try {
    const { id } = req.params;
    const auditors = getAuditorsFromFile();

    // 查找指定ID的用户
    const auditor = auditors.find(u => u.id === id);

    if (!auditor) {
      return res.status(404).json({
        success: false,
        error: '用户不存在'
      });
    }

    return res.status(200).json({
      success: true,
      data: auditor
    });
  } catch (error) {
    console.error('Error getting auditor by id:', error);
    return res.status(500).json({
      success: false,
      error: '获取用户信息失败'
    });
  }
};

/**
 * 注册用户
 * @route POST /api/auditors
 * @param {object} auditor - 用户信息
 * @returns {object} 注册结果
 */
export const registerAuditor = (req, res) => {
  try {
    const auditors = getAuditorsFromFile();
    const newAuditor = req.body;

    // 检查用户是否已存在
    const existingAuditor = auditors.find(u => u.auditorname === newAuditor.auditorname);
    if (existingAuditor) {
      return res.status(400).json({
        success: false,
        error: '用户已存在'
      });
    }

    // 添加新用户
    auditors.push(newAuditor);
    fs.writeFileSync(path.join(__dirname, '../data/users.json'), JSON.stringify(auditors, null, 2));

    return res.status(201).json({
      success: true,
      data: newAuditor
    });
  } catch (error) {
    console.error('Error registering auditor:', error);
    return res.status(500).json({
      success: false,
      error: '注册用户失败'
    });
  }
};

// 登录接口
export const loginAuditor = (req, res) => {
  try {
    const { auditorname, password } = req.body;
    const auditors = getAuditorsFromFile();
    // 查找匹配的用户
    const auditor = auditors.find(u => u.auditorname === auditorname && u.password === password);
    if (!auditor) {
      console.log("auditorcontroller文件中登录失败", res.status(401).json({ success: false, error: '用户名或密码错误' }));
      return res.status(401).json({ success: false, error: '用户名或密码错误' });
    }

    // 登录成功返回当前用户信息（不返回密码）
    const { password: _, ...auditorInfo } = auditor;
    return res.status(200).json({ success: true, data: auditorInfo });
  } catch (error) {
    console.error('Error logging in:', error);
    return res.status(500).json({ success: false, error: '登录失败' });
  }
};

/**
 * 获取用户列表
 * @route GET /api/auditors
 * @returns {object} 用户列表
 */
export const getAuditors = (req, res) => {
  try {
    const auditors = getAuditorsFromFile();
    return res.status(200).json({
      success: true,
      data: auditors
    });
  } catch (error) {
    console.error('Error getting auditors:', error);
    return res.status(500).json({
      success: false,
      error: '获取审核员列表失败'
    });
  }
};
